/*
 * 文件名：SystemServiceImpl.java
 * 版权：Copyright by will_awoke
 * 描述：
 * 修改人：will_awoke
 * 修改时间：2014-8-18
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.qbgs.rbac.service.impl;


import static com.qbgs.util.ReflectUtil.reflect;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qbgs.rbac.bean.SysMenu;
import com.qbgs.rbac.dao.SystemDao;
import com.qbgs.rbac.service.SystemService;
import com.qbgs.security.MD5;


/**
 * 
 * @author will_awoke
 * @version 2014-8-18
 * @see SystemServiceImpl
 * @since
 */
@Service(value = "systemService")
public class SystemServiceImpl implements SystemService
{

    @Autowired
    private SystemDao systemDao;

    @Override
    public boolean isExists(String loginName, String pw)
    {
        return systemDao.queryByLoginNameAndPw(loginName, MD5.toMD5(pw)) > 0;
    }

    @Override
    public boolean isUrlInUserLimit(String loginName, String url)
    {
        return systemDao.isUrlInUserLimit(loginName, url) > 0;
    }

    @Override
    public List<SysMenu> queryNaviJsonByUser(String loginName)
    {
        List<Map<String, Object>> mapList = systemDao.queryNaviByUser(loginName);

        List<SysMenu> meunList = new LinkedList<SysMenu>();
        for (Map<String, Object> jdbcMapResult : mapList)
        {
            // 利用工具类反向生成bean
            meunList.add(reflect(SysMenu.class, jdbcMapResult));
        }
        List<SysMenu> jsonList = new LinkedList<SysMenu>();
        Map<String, String> atts = null;
        List<SysMenu> children = null;

        for (SysMenu menu : meunList)
        {
            // 设置 url attributes
            atts = new LinkedHashMap<String, String>();
            atts.put("url", menu.getMenuUrl());
            menu.setAttributes(atts);
        }
        // 根据easyUI Tree要求拼装 json
        for (SysMenu menu : meunList)
        {
            // 一级菜单 parentId=-1
            if (("-1").equals(menu.getParentId()))
            {
                children = new LinkedList<SysMenu>();

                // TODO 导航菜单暂定共两级（综合easyUI Tree），这里嵌套一次。
                for (SysMenu inner : meunList)
                {
                    // 父id与外层一致id，则将inner添加为外层的children
                    if (inner.getParentId().equals(menu.getId()))
                    {
                        children.add(inner);
                    }
                }
                menu.setChildren(children);

                // add to jsonList
                jsonList.add(menu);
            }
        }
        return jsonList;
    }

    @Override
    public List<String> queryButtonsOfFunc(String loginName, String funcUrl)
    {
        return systemDao.queryButtonsOfFunc(loginName, funcUrl);
    }

}
